package com.yum.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yum.common.utils.Md5Utils;
import com.yum.common.utils.Utils;
import com.yum.system.entity.SysUser;
import com.yum.system.mapper.SysUserMapper;
import com.yum.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Package: com.yum.system.system.impl
 * Description： TODO
 * Author: Forest
 * Date: Created in 2021/3/28 14:53
 * Version: 0.0.1
 * Modified By: duforest
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<SysUser> selectUserList(SysUser sysUser) {
        log.info("selectUserList,sysUser={}", sysUser);
        List<SysUser> sysUsers = sysUserMapper.selectUserList(sysUser);
        log.info("selectUserList finish,sysUsers={}", sysUsers);
        return sysUsers;
    }

    @Override
    public SysUser selectUserById(Long userId) {
        checkReqParam(userId);
        log.info("selectUserById,userId={}", userId);
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        log.info("selectUserById finish,sysUser={}", sysUser);
        return sysUser;
    }

    @Transactional
    @Override
    public int deleteUserById(Long userId) {
        checkReqParam(userId);
        log.info("deleteUserById,userId={}", userId);
        int num = sysUserMapper.deleteUserById(userId);
        log.info("deleteUserById finish,result={}", num);
        return num;
    }


    @Transactional
    @Override
    public int updateUser(SysUser user) {
        checkReqParam(user.getUserId());
        if (Utils.isNotEmpty(user.getPassWord())) {
            user.setPassWord(Md5Utils.passwordEncoder(user.getPassWord()));
        }
        user.setUpdateTime(new Date());
        log.info("updateUser,user={}", user);
        int num = sysUserMapper.updateUser(user);
        log.info("updateUser finish,result={}", num);
        return num;
    }

    @Transactional
    @Override
    public int insertUser(SysUser user) {
        log.info("insertUser,user={}", user);
        user.setPassWord(Md5Utils.passwordEncoder(user.getPassWord()));
        user.setCreateTime(new Date());
        int num = sysUserMapper.insertUser(user);
        log.info("insertUser finish,result={}", num);
        return num;
    }

    private void checkReqParam(Long userId) {
        if (Utils.isNull(userId)) {
            throw new RuntimeException("缺少必填参数");
        }
    }
}
